package com.qingyun.web.controller.wxapi;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingyun.common.annotation.RepeatSubmit;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.exception.CustomException;
import com.qingyun.common.exception.ServiceException;
import com.qingyun.common.utils.PageUtils;
import com.qingyun.security.controller.BaseController;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokActivity;
import com.qingyun.shop.domain.TiktokActivityToCoupon;
import com.qingyun.shop.domain.TiktokCoupon;
import com.qingyun.shop.domain.bo.coupon.TiktokAppCouponAddBo;
import com.qingyun.shop.domain.bo.coupon.TiktokAppCouponQueryBo;
import com.qingyun.shop.domain.bo.coupon.TiktokCouponBo;
import com.qingyun.shop.domain.vo.TiktokAppCouponListVo;
import com.qingyun.shop.domain.vo.TiktokCouponVo;
import com.qingyun.shop.mapper.TiktokActivityMapper;
import com.qingyun.shop.mapper.TiktokActivityToCouponMapper;
import com.qingyun.shop.mapper.TiktokCouponMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

@Api(tags = "小程序-优惠券api")
@RequestMapping("/miniapp/coupon")
@RestController
@AllArgsConstructor
public class ShopCouponController extends BaseController {

    private final TiktokCouponMapper couponMapper;

    private final MapperFacade mapperFacade;

    private final TiktokActivityMapper activityMapper;

    private final TiktokActivityToCouponMapper activityToCouponMapper;

    @ApiOperation("优惠券列表")
    @GetMapping("/list")
    public TableDataInfo<TiktokAppCouponListVo> list(TiktokAppCouponQueryBo bo) {

        Long shopId = SecurityUtils.getAppLoginUser().getShop().getId();

        bo.setShopId(shopId);

        Page<TiktokAppCouponListVo> results = couponMapper.selectAppCouponList(PageUtils.buildPage(), bo);

        return PageUtils.buildDataInfo(results);
    }

    @ApiOperation("获取有效期剩余优惠券张数 （过期和下架的优惠券不参与计算）")
    @GetMapping("/residueCount")
    public AjaxResult<Long> residue() {
        Long shopId = SecurityUtils.getAppLoginUser().getShop().getId();
        Long count = couponMapper.getResidueByShopId(shopId);
        return AjaxResult.success(count);
    }

    @ApiOperation("查看详情")
    @GetMapping("/detail/{id}")
    public AjaxResult<TiktokCouponVo> detail(@PathVariable("id") Long id) {
        TiktokCoupon coupon = couponMapper.selectById(id);
        return AjaxResult.success(mapperFacade.map(coupon, TiktokCouponVo.class));
    }

    @ApiOperation("添加优惠券")
    @RepeatSubmit()
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult<Void> add(@Valid @RequestBody TiktokAppCouponAddBo addBo) {

        TiktokCoupon coupon = mapperFacade.map(addBo, TiktokCoupon.class);

        validEntityBeforeSave(coupon);

        return toAjax(couponMapper.insert(coupon) > 0);
    }

    @ApiOperation("修改优惠券")
    @RepeatSubmit()
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult<Void> edit(@Valid @RequestBody TiktokCouponBo editBo) {
        TiktokCoupon coupon = mapperFacade.map(editBo, TiktokCoupon.class);

        validEntityBeforeSave(coupon);

        return toAjax(couponMapper.updateById(coupon) > 0);
    }

    @ApiOperation("修改优惠券状态 0待上架 3已下架")
    @PostMapping("/modifiStatus")
    public AjaxResult<Void> modifyStatus(@RequestParam("id") Long id,
                                         @RequestParam("status") Integer status) {
        if (status == 0 || status == 2) {
            return AjaxResult.error("参数错误");
        }
        TiktokActivityToCoupon activityToCoupon = activityToCouponMapper.selectOne(Wrappers.query(new TiktokActivityToCoupon().setCouponId(id)));
        if (activityToCoupon != null) {
            TiktokActivity tiktokActivity = activityMapper.selectById(activityToCoupon.getActivityId());
            if (tiktokActivity.getStatus() == 2) {
                throw new ServiceException("优惠券已经关联了已上线的活动，不能下架");
            }
        }

        TiktokCoupon coupon = new TiktokCoupon();
        coupon.setId(id);
        coupon.setStatus(status);

        return toAjax(couponMapper.updateById(coupon) > 0);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TiktokCoupon entity) {
        if (entity.getTimeType().equals(0)) {
            if (entity.getDays() < 0) {
                throw new ServiceException("优惠卷有效时间不能小于0", HttpStatus.HTTP_BAD_REQUEST);
            }
            entity.setStartTime(new Date());
            entity.setEndTime(DateUtil.offsetDay(new Date(), entity.getDays()));
        } else {
            if (ObjectUtil.isNull(entity.getStartTime()) || ObjectUtil.isNull(entity.getEndTime())) {
                throw new ServiceException("开始时间和结束时间不能为空", HttpStatus.HTTP_BAD_REQUEST);
            }
            if (entity.getEndTime().before(entity.getStartTime())) {
                throw new ServiceException("结束日期不能在开始日期之前", HttpStatus.HTTP_BAD_REQUEST);
            }
            if (entity.getEndTime().before(new Date())) {
                throw new CustomException("优惠卷过期时间不能在当前时间之前");
            }
        }

        if (ObjectUtil.isNull(entity.getCollectionTimes())) {
            entity.setCollectionTimes(1);
        }
    }

}
